package com.ctcc.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Objects;

public class AESEncryptor {
    private static final Charset CHARSET = StandardCharsets.UTF_8;
    private static final String ALGORITHM = "AES";

    private String aesKey;

    public AESEncryptor(String aesKey) {
        this.aesKey = Objects.requireNonNull(aesKey, "aesKey为null");
    }

    /**
     * 加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public String encrypt(String data) {
        byte[] ciperData = encrypt(data.getBytes(CHARSET));
        return Base64.encodeBase64String(ciperData);
    }

    /**
     * <p>
     * 加密
     * </p>
     *
     * @param data
     * @return
     * @throws Exception
     */
    public byte[] encrypt(byte[] data) {
        Key k = new SecretKeySpec(aesKey.getBytes(CHARSET), ALGORITHM);
        byte[] raw = k.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public String decrypt(String data) {
        byte[] plainData = decrypt(Base64.decodeBase64(data));
        return new String(plainData, CHARSET);
    }

    /**
     * <p>
     * 解密
     * </p>
     *
     * @param data
     * @return
     * @throws Exception
     */
    public byte[] decrypt(byte[] data) {
        Key k = new SecretKeySpec(aesKey.getBytes(CHARSET), ALGORITHM);
        byte[] raw = k.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
    	//开发者key
        AESEncryptor encryptor = new AESEncryptor("4frTIZIpiGxDMXfk");
        //得到的requestBody密文参数
        String requestBody = "";
        String json = encryptor.decrypt(requestBody);
        System.out.println(json);
    }
}